/**
 *  创建后台UI的侧边栏组件
 *  by 李锐
 *  date: 2018/09/08
 **/
layui.define(['element', 'exception', 'common'], function (exports) {
    "use strict";
    var $ = layui.jquery,
        element = layui.element,
        exception = layui.exception,
        common = layui.common,
        cacheName = 'gtmap-sidebar';

    var SideBar = function () {
        this.info = {
            name: 'SideBar',
            version: 'v1.1',
            el: '#gtmap-sidebar',//默认容器
            data: 'main/loadSideBarNodes'
        };
        this.config = {
            el: undefined,
            data: undefined
        };
    };
    //渲染
    SideBar.prototype.render = function (options,callback) {
        var _that = this;
        var _config = _that.config;
        if (options === undefined || options === null) {
            //如果未配置
            _config.el = _that.info.el;
            _config.data = _that.info.data;
        } else {
            _that.config.data = undefined;
            $.extend(true, _that.config, options);
        }
        var $container = common.getContainer(_that);
        if ($container === null) {
            return;
        }
        //检查是否存在缓存
        var sideBarData = null;
        var cache = layui.data(cacheName);
        if (cache !== undefined && cache !== null && cache.value !== undefined && cache.value !== null) {
            sideBarData = cache;
        } else if (_config.data !== undefined && _config.data !== null) {
            $.ajax({
                type: 'get',
                url: _config.data,
                async: false,
                dataType: 'json',
                success: function (res, status, xhr) {
                    if (res.code === 0) {
                        //添加缓存
                        // layui.data('test',res);
                       // console.log(res.data);
                        sideBarData = res.data;
                    }
                },
                error: function (xhr, status, error) {
                    exception.throwError("SideBar Error:" + error);
                },
                complete: function (xhr, status) {
                    _that.config.el = $container;
                }
            });
        } else {
            exception.throwDataCinfigError(_that, 'data');
        }

        var html = getHtml(sideBarData);
        $container.html(html);
        element.init();
        if(!isEmpty(callback)){
        	      var firstTab={};
			       if(sideBarData[0].children.length>0){
			        	if(sideBarData[0].children[0].length>0){
			        		firstTab.href=sideBarData[0].children[0].children[0].href;
			        		firstTab.icon=sideBarData[0].children[0].children[0].icon;
			        		firstTab.title=sideBarData[0].children[0].children[0].title;
			        	}else{
			        		firstTab.href=sideBarData[0].children[0].href;
			        		firstTab.icon=sideBarData[0].children[0].icon;
			        		firstTab.title=sideBarData[0].children[0].title;
			        	}
			        }else{
			        	firstTab.href=sideBarData[0].href;
			    		firstTab.icon=sideBarData[0].icon;
			    		firstTab.title=sideBarData[0].title;
			        }
			        callback(firstTab);
        }
		        /**
		 * 判空
		 * @param {Object} str
		 */
		function isEmpty(str) {
			if(str == null || typeof(str) == 'undefined' || str == 'null' || str == '(null)' || str == '<null>' || str == 'undefined' || str == 'NULL' || str == undefined || str.length == 0) {
				return true;
			}
			if(typeof(str) == 'string' && str.replace(/(^s*)|(s*$)/g, "").length == 0) {
				return true;
			}
			if(typeof(str) == 'number' && str == 0) {
				return true;
			}
			return false;
		}
  
    };

    /**
     * 绑定事件
     * @param {String} events
     * @param {Function} callback
     */
    SideBar.prototype.on = function (events, callback) {
        var that = this;
        if (that.config.el === undefined && that.config.el === null) {
            that.config.el = that.info.el
        }
        var _con = that.config.el;
        if (typeof (events) !== 'string') {
            common.throwError('SideBar error:事件名配置出错，请参考API文档.');
        }
        var lIndex = events.indexOf('(');
        var eventName = events.substr(0, lIndex);
        var filter = events.substring(lIndex + 1, events.indexOf(')'));
        //点击事件
        if (eventName === 'click') {
        	
            if (_con.attr('lay-filter') !== undefined) {
                _con.find('.layui-side-scroll li').each(function () {
                    var $this = $(this);
                    //一级列表
                    if ($this.find('dl').length == 0) {
                        $this.on('click', function () {
                        	
                            var $a = $this.children('a');
                            var href = $a.data('url');
                            var icon = $a.children('i:first').data('icon');
                            var title = $a.children('cite').text();
                            var pTitle = $a.attr('ptitle');
                            var pUrl = $a.attr('purl');
                            var data = {
                                elem: $a,
                                field: {
                                    href: href,
                                    icon: icon,
                                    title: title,
                                    pTitle:pTitle,
                                    pUrl:pUrl
                                }
                            }
                            callback(data);
                        });
                        //二级列表
                    } else if ($this.find('dl').length > 0) {
                        var $dd = $this.find('dd').each(function () {
                            if(!$(this).children("dl").length>0){
                                $(this).on('click', function () {
                                    var $a = $(this).children('a');
                                    var href = $a.data('url');
                                    var icon = $a.children('i:first').data('icon');
                                    var title = $a.children('cite').text();
                                    var pTitle = $a.attr('ptitle');
		                            var pUrl = $a.attr('purl');
		                            var data = {
		                                elem: $a,
		                                field: {
		                                    href: href,
		                                    icon: icon,
		                                    title: title,
		                                    pTitle:pTitle,
		                                    pUrl:pUrl
		                                }
		                            }
                                    callback(data);
                                });
                            }
                        });
                        //三级列表
                    } else if ($this.find('dd').children('dl').length > 0) {
                        var $dd = $this.find('dd').children('dl').find('dd').each(function () {
                            $(this).on('click', function () {
                                var $a = $(this).children('a');
                                var href = $a.data('url');
                                var icon = $a.children('i:first').data('icon');
                                var title = $a.children('cite').text();
                                var pTitle = $a.attr('ptitle');
	                            var pUrl = $a.attr('purl');
	                            var data = {
	                                elem: $a,
	                                field: {
	                                    href: href,
	                                    icon: icon,
	                                    title: title,
	                                    pTitle:pTitle,
	                                    pUrl:pUrl
	                                }
	                            }
                                callback(data);
                            });
                        })
                    }
                });
            }
        }
    };
    /**
     * 清除缓存
     */
    SideBar.prototype.cleanCached = function () {
        layui.data(cacheName, null);
    };

    /**
     * 获取html字符串
     * @param {Object} data
     */
    function getHtml(data) {
        //debugger;
        var ulHtml = '<div class="layui-side-scroll"><ul class="layui-nav layui-nav-tree beg-navbar">';
        for (var i = 0; i < data.length; i++) {
            if (data[i].spread) {
            	if(data[i].children==""||data[i].children==null||data[i].children=="null"||data[i].children=="undefined"){
            		if(i=="0"){
            			ulHtml += '<li class="layui-nav-item layui-this">';
            		}else{
            			ulHtml += '<li class="layui-nav-item">';
            		}
            	}else{
            		ulHtml += '<li class="layui-nav-item layui-nav-itemed">';
            	}
                
            } else {
        			ulHtml += '<li class="layui-nav-item">';
            }
            var dataUrl = (data[i].href !== undefined && data[i].href !== '') ? 'data-url="' + data[i].href + '"' : '';
//      	ulHtml += '<a href="javascript:;">';
        	ulHtml += '<a href="javascript:;" ' + dataUrl + 'pUrl="" pTitle="">';
            if (data[i].icon !== undefined && data[i].icon !== '') {
                if (data[i].icon.indexOf('fa-') !== -1) {
                    ulHtml += '<i class="fa ' + data[i].icon + '" aria-hidden="true" data-icon="' + data[i].icon + '"></i>';
                } else if(data[i].icon.indexOf('layui-')!== -1){
                    ulHtml += '<i class="layui-icon" data-icon="' + data[i].icon + '">' + data[i].icon + '</i>';
                } else if(data[i].icon.indexOf('icon-')!== -1){
                	if(data[i].icon.indexOf('iconfont')!== -1){
                		ulHtml += '<i class="'+data[i].icon+'" data-icon="' + data[i].icon + '"></i>';
                	}else{
                		ulHtml += '<i class="iconfont '+data[i].icon+'" data-icon="' + data[i].icon + '"></i>';
                	}
                }else{
                	ulHtml += '<i class="'+data[i].icon+'" data-icon="' + data[i].icon + '"></i>';
                }
            }else{
            	ulHtml += '<i class="iconfont icon-tongyong"></i>';
            }
            ulHtml += '<cite>' + data[i].title + '</cite>';
//              ulHtml += '<span class="layui-icon layui-icon-right"></span>';
            ulHtml += '</a>';
            if (data[i].children !== undefined && data[i].children !== null && data[i].children.length > 0) {
                ulHtml += '<dl class="layui-nav-child">'
                for (var j = 0; j < data[i].children.length; j++) {
                	
                	if(data[i].children[j].spread){
                		 if(i==0&&j==0){
	                    	if(data[i].children[j].children!== undefined && data[i].children[j].children !== null && data[i].children[j].children.length  > 0){
	                    		ulHtml += '<dd title="' + data[i].children[j].title + '" class="layui-nav-itemed">';
	                    		console.log("fdsafsda");
	                    	}else{
	                    		ulHtml += '<dd title="' + data[i].children[j].title + '" class="layui-this">';
	                    		console.log("000000");
	                    	}
	                    }else{
	                    	ulHtml += '<dd title="' + data[i].children[j].title + '">';
	                    }
                	}else{
                		ulHtml += '<dd title="' + data[i].children[j].title + '">';
                	}
                	
                   
                    if (data[i].children[j].href !== undefined) {
                        ulHtml += '<a href="javascript:;" data-url="' + data[i].children[j].href + '"  pUrl="'+data[i].href+'" pTitle="'+data[i].title+'">';
                    } else {
                        ulHtml += '<a href="javascript:;"  pUrl="'+data[i].href+'" pTitle="'+data[i].title+'">';
                    }
                    if (data[i].children[j].icon !== undefined && data[i].children[j].icon !== '') {
                        if (data[i].children[j].icon.indexOf('fa-') !== -1) {
                            ulHtml += '<i class="fa ' + data[i].children[j].icon + '" data-icon="' + data[i].children[j].icon + '" aria-hidden="true"></i>';
                        } else if(data[i].children[j].icon.indexOf('icon-')!== -1){
		                	if(data[i].children[j].icon.indexOf('iconfont')!== -1){
		                		ulHtml += '<i class="'+data[i].children[j].icon+'" data-icon="' + data[i].children[j].icon + '"></i>';
		                	}else{
		                		ulHtml += '<i class="iconfont '+data[i].children[j].icon+'" data-icon="' + data[i].children[j].icon + '"></i>';
		                	}
		                }else if(data[i].children[j].icon.indexOf('layui-')!== -1){
	                        ulHtml += '<i class="layui-icon" data-icon="' + data[i].children[j].icon + '">' + data[i].children[j].icon + '</i>';
	                    }else{
	                    	ulHtml += '<i class="iconfont icon-tongyong"></i>';
	                    }
                    }
                    ulHtml += '<cite>' + data[i].children[j].title + '</cite>';
                    ulHtml += '</a>';
                    if (data[i].children[j].children !== undefined && data[i].children[j].children !== null && data[i].children[j].children.length > 0) {
                        ulHtml += '<dl class="layui-nav-child">';
                        for (var k = 0; k < data[i].children[j].children.length; k++) {
                        	 if(i==0&&j==0&&k==0){
		                    	ulHtml += '<dd class="layui-this" title="' + data[i].children[j].children[k].title + '">';
		                    }else{
		                    	 ulHtml += '<dd title="' + data[i].children[j].children[k].title + '">';
		                    }
                            ulHtml += '<a href="javascript:;" data-url="' + data[i].children[j].children[k].href + '"  pUrl="'+data[i].children[j].href+'" pTitle="'+data[i].children[j].title+'">';
                            if (data[i].children[j].icon !== undefined && data[i].children[j].icon !== '') {
                                if (data[i].children[j].children[k].icon.indexOf('fa-') !== -1) {
                                    ulHtml += '<i class="fa ' + data[i].children[j].children[k].icon + '" data-icon="' + data[i].children[j].children[k].icon + '" aria-hidden="true"></i>';
                                } else if(data[i].children[j].children[k].icon.indexOf('icon-')!== -1){
				                	if(data[i].children[j].children[k].icon.indexOf('iconfont')!== -1){
				                		ulHtml += '<i class="'+data[i].children[j].children[k].icon+'" data-icon="' + data[i].children[j].children[k].icon + '"></i>';
				                	}else{
				                		ulHtml += '<i class="iconfont '+data[i].children[j].children[k].icon+'" data-icon="' + data[i].children[j].children[k].icon + '"></i>';
				                	}
				                }else if(data[i].children[j].children[k].icon.indexOf('layui-')!== -1){
			                        ulHtml += '<i class="layui-icon" data-icon="' + data[i].children[j].children[k].icon + '">' + data[i].children[j].children[k].icon + '</i>';
			                    }else{
			                    	ulHtml += '<i class="iconfont icon-tongyong"></i>';
			                    }
                            }
                            ulHtml += '<cite>' + data[i].children[j].children[k].title + '</cite>';
                            ulHtml += '</a></dd>';
                        }
                        ulHtml += '</dl>';
                    }

                    ulHtml += '</dd>';
                }
                ulHtml += '</dl>';
            } 
//          else {
//              var dataUrl = (data[i].href !== undefined && data[i].href !== '') ? 'data-url="' + data[i].href + '"' : '';
//              ulHtml += '<a href="javascript:;" ' + dataUrl + '>';
//              if (data[i].icon !== undefined && data[i].icon !== '') {
//                  if (data[i].icon.indexOf('fa-') !== -1) {
//                      ulHtml += '<i class="fa ' + data[i].icon + '" aria-hidden="true" data-icon="' + data[i].icon + '"></i>';
//                  } else if(data[i].icon.indexOf('layui-')!== -1){
//                      ulHtml += '<i class="layui-icon" data-icon="' + data[i].icon + '">' + data[i].icon + '</i>';
//                  }else{
//                  	ulHtml += '<i class="'+data[i].icon+'" data-icon="' + data[i].icon + '"></i>';
//                  }
//              }
//              ulHtml += '<cite>' + data[i].title + '</cite>';
//              
////              ulHtml += '<span class="layui-icon layui-icon-right"></span>';
//              ulHtml += '</a>';
//          }
            ulHtml += '</li>';
        }
        ulHtml += '</ul></div>';

        return ulHtml;
    }

    var sidebar = new SideBar();

    exports('sidebar', sidebar);
})
;